var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')

var loginRouter = require('./routes/login')
var blogRouter = require('./routes/blog')
var blogRollRouter = require('./routes/blogRoll')
var totalRollRouter = require('./routes/total')
var app = express()

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

// 登录路由
app.use('/', loginRouter)
// 博客路由
app.use('/', blogRouter)
// 友链
app.use('/', blogRollRouter)
// 首页统计
app.use('/', totalRollRouter)

app.use(function (req, res, next) {
  next(createError(404))
})

app.use(function (err, req, res, next) {
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  res.status(err.status || 500)
  res.send({
    ok: -1,
    msg: '服务器异常,请稍后再试',
  })
})

module.exports = app
